package myJDBC.lowLevel;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import myJDBC.myConnection;

public class AttrTypeDef {

	public static void createAttrTypeDef(int attrId, String name, String[] values) throws SQLException{
		int tmp;
		PreparedStatement pstmt = null;
		try {
			pstmt = myConnection.dbConnection
					.prepareStatement("insert into \"attr_type_def\"(\"attr_type_def_id\",\"name\",\"list_value_id\") values (?,?,?)");
			for(int i=0; i<values.length;i++){
				tmp=ListValues.createValue(i+1, values[i]);
				pstmt.setInt(1, attrId);
				pstmt.setString(2, name);
				pstmt.setInt(3, tmp);
				pstmt.executeUpdate();
			}
		} finally {
			if (pstmt != null)
				pstmt.close();
		}		
	}
	
	public static ArrayList<String> returnAtrListValues(int attrId){
		ArrayList<String> al = new ArrayList<String>();
		StringBuilder selectAttributes = new StringBuilder();
		    selectAttributes.append("select t1.\"list_value_id\", t2.\"value\" ")
							.append("from \"attr_type_def\" t1 ")
							.append("left join ")
							.append("\"list_values\" t2 ")
							.append("on t1.\"list_value_id\"=t2.\"list_value_id\" ")
							.append("where t1.\"attr_type_def_id\"=? ");
		if (myConnection.dbConnection != null) {
		    try (PreparedStatement pstmt = myConnection.dbConnection
		                .prepareStatement(selectAttributes.toString())) {
				   pstmt.setInt(1, attrId);
				   pstmt.executeUpdate(); 
				   ResultSet rs = pstmt.executeQuery();	
				String tmp;
				while (rs.next()) {
					tmp = Integer.toString(rs.getInt(1));
					al.add(tmp);
					tmp = rs.getString(2);
					al.add(tmp);
				}
			} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
			return al;
		} else
			return null;		
	}
}
